//
//  YXBaseDownloadTool.m
//  MockProject
//
//  Created by FanYu on 30/8/2016.
//  Copyright © 2016 niuzhaowang. All rights reserved.
//

#import "YXBaseDownloadTool.h"
#import "AFNetworking.h"
#import "YXTool.h"

@interface YXBaseDownloadTool ()

@end


@implementation YXBaseDownloadTool

+ (void)head:(NSString *)url params:(NSDictionary *)params success:(void (^)(NSString *))sizeBytes failure:(void (^)(NSError *))failure {
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session HEAD:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task) {
        sizeBytes([YXTool sizeStringForBytes:[task.response expectedContentLength]]);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}


+ (NSURLSessionDownloadTask *)download:(NSString *)url progress:(void (^)(id))progress failure:(void (^)(NSError *))failure filePath:(void (^)(id))path {
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress) {
        // 进度
        progress(downloadProgress);
        
    } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
        
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        failure(error);
        path(filePath);
    }];
    
    return downloadTask;
}

@end
